package com.djhu.freepartner.web.service.impl;


import com.djhu.freepartner.web.service.IPushMsgService;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tencent.xinge.XingeApp;
import com.tencent.xinge.bean.AudienceType;
import com.tencent.xinge.bean.Message;
import com.tencent.xinge.bean.MessageAndroid;
import com.tencent.xinge.bean.Platform;
import com.tencent.xinge.push.app.PushAppRequest;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

@Service
@Slf4j
public class XingePushMsgService implements IPushMsgService {

    @Autowired
    private XingeApp  app;

    @Override
    public String pushMsgByToken(String title, String msg, String token) {
        PushAppRequest pushAppRequest = new PushAppRequest();
        pushAppRequest.setAudience_type(AudienceType.token);
        pushAppRequest.setPlatform(Platform.android);
        pushAppRequest.setEnvironment(null);
        ArrayList<String> tokenList = new ArrayList<>();
        tokenList.add(token);
        pushAppRequest.setToken_list(tokenList);
        Message message = new Message();
        message.setTitle(title);
        message.setContent(msg);
        message.setAndroid(new MessageAndroid());
        pushAppRequest.setMessage(message);

        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        String req = null;
        try {
            req = mapper.writeValueAsString(pushAppRequest);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            log.error("parse json",e);
        }
        log.info("pushAppRequest string is {}",req);
        JSONObject retJson = app.pushApp(req);
        return retJson.toString();
    }

    @Override
    public String pushMsgByUser(String title, String msg, String user) {
        return null;
    }

    public static void main(String[] args) {
        String token = "111";
        String title = "test";
        String msg = "test";
        PushAppRequest pushAppRequest = new PushAppRequest();
        pushAppRequest.setAudience_type(AudienceType.token);
        ArrayList<String> tokenList = new ArrayList<>();
        tokenList.add(token);
        pushAppRequest.setToken_list(tokenList);
        Message message = new Message();
        message.setTitle(title);
        message.setContent(msg);
        message.setAndroid(new MessageAndroid());
        pushAppRequest.setMessage(message);
        System.out.println(pushAppRequest.toString());
    }
}
